﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GRTVPluginConsole.Entity;

namespace GRTVPluginConsole.Camera
{
    class CycleTopDriversCamera:AutoCameraEngine
    {
        int viewedSlotId = -1;
        int cameraType;
        bool excludePit;
        int frequencySecond;
        int nbDrivers;
        long lastCameraChange;

        public CycleTopDriversCamera(int cameraType, bool excludePit, int frequencySecond, int nbDrivers)
            : base()
        {
            this.cameraType = cameraType;
            this.excludePit = excludePit;
            this.frequencySecond = frequencySecond;
            this.nbDrivers = nbDrivers;
        }

        public override void DoCheck()
        {
            if (DateTime.Now.Ticks - lastCameraChange >= frequencySecond * 10000000)
            {
                if (Program.DriverList.Count > 0)
                {
                    lastCameraChange = DateTime.Now.Ticks;
                    // search current viewed driver index
                    int currentIndex = -1;
                    int indexDriver = -1;
                    for (int i = 0; i < Program.DriverList.Count; i++)
                    {
                        DriverRank dr = Program.DriverList[i];
                        if (dr != null) {
                            indexDriver++;
                            if (viewedSlotId == dr.slotId)
                            {
                                currentIndex = i;
                                break;
                            }
                        }
                    }
                    if (currentIndex + 1 >= nbDrivers) // test if it is the last allowed top driver (or ever more)
                    {
                        currentIndex = -1; // restart from first list index, as we need to loop
                    }
                    int nb = Program.DriverList.Count;
                    for (int i = 0; i < nb; i++)
                    {
                        currentIndex++;
                        DriverRank dr = Program.DriverList[currentIndex % nb];
                        if (dr != null && (!excludePit || !dr.isInPit) && dr.finishStatus <= 1)
                        {
                            viewedSlotId = dr.slotId;
                            Program.ViewDriver(viewedSlotId, cameraType);
                            break;
                        }
                    }
                }
            }
        }

        public override void Reset()
        {
            viewedSlotId = -1;
            lastCameraChange = 0;
        }
    }
}
